package com.project.lk.nurseapp.common.view.chat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.common.view.chat.voice.MediaPlayerManager;
import com.project.lk.nurseapp.healthrecord.HealthRecordActivity;
import com.project.lk.nurseapp.home.MainActivity;
import com.project.lk.nurseapp.inputfiles.InputFilesActivity;
import com.project.lk.nurseapp.nurse.doctorapply.DoctorListActivity;
import com.project.lk.nurseapp.utils.GlideCircleTransform;
import com.project.lk.nurseapp.utils.MediaUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;
import com.project.lk.nurseapp.utils.VoiceAnimUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.project.lk.nurseapp.base.BaseApi.audio_type;
import static com.project.lk.nurseapp.base.BaseApi.image_type;
import static com.project.lk.nurseapp.base.BaseApi.register_fail;
import static com.project.lk.nurseapp.base.BaseApi.text_type;
import static com.project.lk.nurseapp.base.BaseApi.video_type;

/**
 * 功能介绍：聊天记录adapter
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class MessageAdapter extends BaseAdapter {

    private Context context;
    private List<IMMessage> data = new ArrayList<>();
    boolean isPlay = false;
    private View view;
    //item的最小宽度
    private int mMinWidth;
    //item的最大宽度
    private int mMaxWidth;
    int count = 0;
    ArrayList<String> mImageList = new ArrayList<>();
    Map<Integer, String> mImageMap = new HashMap<>();

    public MessageAdapter(Context context, List<IMMessage> list) {
        super();
        this.context = context;
        this.data = list;
        //获取屏幕的宽度
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        //最大宽度为屏幕宽度的百分之七十
        mMaxWidth = (int) (outMetrics.widthPixels * 0.7f);
        //最大宽度为屏幕宽度的百分之十五
        mMinWidth = (int) (outMetrics.widthPixels * 0.15f);
    }

    public void setList(List<IMMessage> list) {
        this.data = list;
    }

    @Override
    public int getCount() {
        return data != null ? data.size() : 0;
    }

    @Override
    public IMMessage getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        IMMessage message = getItem(position);
        return TextUtils.equals(message.getSenderId(), new UserInfoUtils().getAccountId()) ? 1 : 0;
    }

    public void setImageList(ArrayList<String> list) {
        mImageList = list;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    public View getHolder() {

        return view;
    }

    public void setViewHolder(View view) {

        this.view = view;
        notifyDataSetChanged();
    }

    public interface ItemEvent {
        void showVipMsg();
    }

    ItemEvent mListenter;

    public void setOnEventListenter(ItemEvent listenter) {
        this.mListenter = listenter;
    }

    @SuppressLint("InflateParams")
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final IMMessage message = data.get(position);
        final int viewType = getItemViewType(position);
        ViewHolder viewHolder = null;
        if (convertView == null) {
            if (viewType == 0) {
                convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_left, null);
            } else {
                convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_right, null);
            }
            viewHolder = new ViewHolder(convertView);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Glide.with(context).load(message.getSenderHeadImg()).bitmapTransform(new GlideCircleTransform(context))
                .placeholder(R.drawable.touxiang)
                .error(R.drawable.touxiang)
                .into(viewHolder.userAvatarImageView);
        viewHolder.userNameTextView.setText(String.valueOf(message.getSenderNickName()));

        try {
            String dateString = DateFormat.format("yyyy-MM-dd h:mmaa", Long.parseLong(message.getTime())).toString();
            viewHolder.sendDateTextView.setText(dateString);
            if (position == 0) {
                viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
            } else {
                viewHolder.sendDateTextView.setVisibility(View.GONE);
            }
        } catch (Exception e) {
        }
        switch (message.getMsgType()) {
            case text_type://text
                viewHolder.msgItemVoiceLayout.setVisibility(View.GONE);
                viewHolder.msgContextLayout.setVisibility(View.VISIBLE);
                viewHolder.textHintLayout.setVisibility(View.GONE);
                viewHolder.vipLayout.setVisibility(View.GONE);
                viewHolder.mapLayout.setVisibility(View.GONE);
                viewHolder.photoImageView.setVisibility(View.GONE);
                viewHolder.videoLayout.setVisibility(View.GONE);
                viewHolder.msgMapImage.setVisibility(View.GONE);
                if (viewType == 0) { //方向
                    viewHolder.msgContextLayout.setBackgroundResource(R.drawable.qipao1);
                    if (TextUtils.equals(message.getSenderNickName(), "提示")
                            && TextUtils.equals(message.getSessionId(), "")
                            && TextUtils.equals(message.getSenderId(), "") && TextUtils.equals(message.getDirect(), "")) {
                        viewHolder.textHintLayout.setVisibility(View.VISIBLE);

//						viewHolder.userAvatarImageView.setOnClickListener(new View.OnClickListener() {
//							@Override
//							public void onClick(View v) {
//								context.startActivity(new Intent(context, DoctorListActivity.class));
//							}
//						});
                        viewHolder.itemHealth.setOnClickListener(new View.OnClickListener() {  //查看健康档案
                            @Override
                            public void onClick(View v) {
                                if (message.getContent().contains("在线模式")) {
                                    context.startActivity(new Intent(context, HealthRecordActivity.class));
                                } else {
                                    ToastUtils.showShortToast("当前处于离线模式，不能使用此功能");
                                }
                            }
                        });

                        viewHolder.itemVip.setOnClickListener(new View.OnClickListener() {  //进入vip
                            @Override
                            public void onClick(View v) {
//								ToastUtils.showShortToast("VIP服务");
                                if (message.getContent().contains("在线模式")) {
                                    mListenter.showVipMsg();
                                } else {
                                    ToastUtils.showShortToast("当前处于离线模式，不能使用此功能");
                                }

                            }
                        });
                        viewHolder.itemRecord.setOnClickListener(new View.OnClickListener() {  //录入健康档案
                            @Override
                            public void onClick(View v) {
                                if (message.getContent().contains("在线模式")) {
                                    context.startActivity(new Intent(context, InputFilesActivity.class));
                                } else {
                                    ToastUtils.showShortToast("当前处于离线模式，不能使用此功能");
                                }
                            }
                        });
                        viewHolder.itemMeasure.setOnClickListener(new View.OnClickListener() { //测量
                            @Override
                            public void onClick(View v) {
                                if (message.getContent().contains("在线模式")) {
                                    context.startActivity(new Intent(context, MainActivity.class).putExtra("login", "login"));
                                } else {
                                    context.startActivity(new Intent(context, MainActivity.class).putExtra("login", "out"));
                                }

                            }
                        });
                    } else if (TextUtils.equals(message.getSenderNickName(), "提示")
                            && TextUtils.equals(message.getSessionId(), "")
                            && TextUtils.equals(message.getSenderId(), "") && TextUtils.equals(message.getDirect(), "vip")) {

                        viewHolder.vipLayout.setVisibility(View.VISIBLE);
                        viewHolder.vipLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                context.startActivity(new Intent(context, DoctorListActivity.class));
                            }
                        });
                    }

                } else {
                    viewHolder.msgContextLayout.setBackgroundResource(R.drawable.qipao);
                }
                MoonUtil.identifyFaceExpression(BaseApp.getContext(), viewHolder.textTextView, message.getContent(), ImageSpan.ALIGN_BOTTOM);

                break;
            case image_type://图片
                viewHolder.msgItemVoiceLayout.setVisibility(View.GONE);
                viewHolder.msgContextLayout.setVisibility(View.GONE);
                viewHolder.textHintLayout.setVisibility(View.GONE);
                viewHolder.vipLayout.setVisibility(View.GONE);
//   ImageAttachment imageAttachment = (ImageAttachment) message.getAttachment();
//  final String path = imageAttachment.getUrl();
//				final String url=((ImageAttachment)data.get(position).getAttachment()).getUrl();
//                String thumbPath = imageAttachment.getPath();
//                if (path.contains("emoji")){
//					viewHolder.photoImageView.setVisibility(View.GONE);
//					viewHolder.faceImageView.setVisibility(View.VISIBLE);
//                    Glide.with(context).load(path).into(viewHolder.faceImageView);
//
//                }else {
                final String thumbPath = message.getContent();
                viewHolder.mapLayout.setVisibility(View.GONE);
                viewHolder.videoLayout.setVisibility(View.GONE);
                viewHolder.photoImageView.setVisibility(View.VISIBLE);
                viewHolder.photoImageView.setFocusable(true);
                if (!TextUtils.isEmpty(thumbPath)) {
                    Glide.with(context).load(thumbPath).error(R.mipmap.default_error)
                            .placeholder(R.mipmap.default_error).into(viewHolder.photoImageView);
                } else {
                    Glide.with(context).load(thumbPath).error(R.mipmap.default_error)
                            .placeholder(R.mipmap.default_error).into(viewHolder.photoImageView);
                }

                if (thumbPath != null) {
                    mImageList.add(thumbPath);
                }


                Log.e("MLOG", mImageList.size() + "");
                //图片点击事件

                viewHolder.photoImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转传递图片集合
                        if (thumbPath != null) {
							Intent intent = new Intent(context, ShowImageActivity.class);
							intent.putExtra("path", thumbPath);
							intent.putExtra("image",mImageList);
							context.startActivity(intent);
                        } else {
                            ToastUtils.showShortToast("图片无效");
                        }

                    }
                });

                //     }


//			//TODO set image
//			int id = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());

                break;

//            case undef://face
////			viewHolder.photoImageView.setVisibility(View.GONE);
////			viewHolder.textTextView.setVisibility(View.GONE);
////			viewHolder.faceImageView.setVisibility(View.VISIBLE);
////			int resId = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
////			viewHolder.faceImageView.setImageResource(resId);
//			break;

            case audio_type: //声音
                viewHolder.mapLayout.setVisibility(View.GONE);
                viewHolder.videoLayout.setVisibility(View.GONE);
                viewHolder.msgContextLayout.setVisibility(View.GONE);
                viewHolder.msgItemVoiceLayout.setVisibility(View.VISIBLE);
                viewHolder.photoImageView.setVisibility(View.GONE);
                viewHolder.recoderTime.setVisibility(View.VISIBLE);
                viewHolder.textHintLayout.setVisibility(View.GONE);
                viewHolder.vipLayout.setVisibility(View.GONE);
//				isOriginImageHasDownloaded(message);
                //语音
//				final AudioAttachment audioAttachment = (AudioAttachment) message.getAttachment();
//
//				AbortableFuture future = NIMClient.getService(MsgService.class).downloadAttachment(message, true);
//				boolean abort = future.abort();
                //http://image.lcc.so/group1/M00/00/04/rBF4W1o7gk-EI69YAAAAAK7sG-s598.amr
//                final String content="http://image.lcc.so/group1/M00/00/04/rBF4W1o7gk-EI69YAAAAAK7sG-s598.amr";
                final String content = message.getContent();
                String ringDuring = MediaUtils.getAudioTime(content);
                if (ringDuring!=null) {
                    viewHolder.recoderTime.setText((Long.parseLong(ringDuring) / 1000) + "\"");
                    ViewGroup.LayoutParams lp = viewHolder.msgVoiceLayout.getLayoutParams();
                    lp.width = (int) (mMinWidth + (mMaxWidth / 60f) * (Long.parseLong(ringDuring) / 1000));
                }

                //设置播放动画以及播放语音
                final ViewHolder finalViewHolder = viewHolder;
                final View finalConvertView = convertView;
                //判断音频是否播放
                viewHolder.msgVoiceLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //播放声音动画
                        VoiceAnimUtils.playVoiceAnim(finalViewHolder.recoderAnim, finalConvertView, viewType);
                        if (MediaPlayerManager.isPlaying()) {

                            if (viewType == 0) {
                                finalViewHolder.recoderAnim.setBackgroundResource(R.drawable.ht01_voice03);
                            } else {
                                finalViewHolder.recoderAnim.setBackgroundResource(R.drawable.ht_voice03);
                            }
                            MediaPlayerManager.pause();
                        } else {
                            // 播放录音
                            MediaPlayerManager.playSound(content, new MediaPlayer.OnCompletionListener() {

                                public void onCompletion(MediaPlayer mp) {
                                    //播放完成后修改图片
                                    if (viewType == 0) {
                                        finalViewHolder.recoderAnim.setBackgroundResource(R.drawable.ht01_voice03);
                                    } else {
                                        finalViewHolder.recoderAnim.setBackgroundResource(R.drawable.ht_voice03);
                                    }
                                }
                            });
                        }

                    }
                });

                break;
            case video_type:
                viewHolder.mapLayout.setVisibility(View.GONE);
                viewHolder.textTextView.setText(message.getContent());
                viewHolder.photoImageView.setVisibility(View.GONE);
                viewHolder.msgItemVoiceLayout.setVisibility(View.GONE);
                viewHolder.msgContextLayout.setVisibility(View.GONE);
                viewHolder.textHintLayout.setVisibility(View.GONE);
                viewHolder.videoLayout.setVisibility(View.VISIBLE);
                viewHolder.vipLayout.setVisibility(View.GONE);
                viewHolder.videoImageView.setFocusable(true);
                final String videoPath = message.getContent();
                if (!TextUtils.isEmpty(videoPath)) {
                    Glide.with(context).load(videoPath).error(R.mipmap.default_error)
                            .placeholder(R.mipmap.default_error).into(viewHolder.videoImageView);
                } else {
//					Glide.with(context).load(videoPath).error(R.mipmap.default_error)
//							.placeholder(R.mipmap.default_error).into(viewHolder.videoImageView);
                }
                viewHolder.videoPlayIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        context.startActivity(new Intent(context, VideoActivity.class)
                                .putExtra("video", videoPath));
                    }
                });

                break;
            default:
                viewHolder.mapLayout.setVisibility(View.GONE);
                viewHolder.textTextView.setText(message.getContent());
                viewHolder.photoImageView.setVisibility(View.GONE);
                viewHolder.videoLayout.setVisibility(View.GONE);
                viewHolder.msgItemVoiceLayout.setVisibility(View.GONE);
                viewHolder.msgContextLayout.setVisibility(View.GONE);
                viewHolder.textHintLayout.setVisibility(View.GONE);
                viewHolder.vipLayout.setVisibility(View.GONE);
                break;


        }
        //消息的状态显示
//		switch (message.getStatus()){
//			case success:
//				viewHolder.failImageView.setVisibility(View.GONE);
//				viewHolder.sendingProgressBar.setVisibility(View.GONE);
//				break;
//			case sending:
//				viewHolder.failImageView.setVisibility(View.GONE);
//				viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
//				Animation operatingAnim = AnimationUtils.loadAnimation(context, R.anim.rotate);
//				viewHolder.sendingProgressBar.startAnimation(operatingAnim);
//				setViewHolder(viewHolder.sendingProgressBar);
//				break;
//			case fail:
//				viewHolder.failImageView.setVisibility(View.VISIBLE);
//				viewHolder.sendingProgressBar.setVisibility(View.GONE);
//				break;
//			case draft:
//				viewHolder.failImageView.setVisibility(View.GONE);
//				viewHolder.sendingProgressBar.setVisibility(View.GONE);
//				break;
//		}
        //viewHolder.textTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

        return convertView;
    }
//
//	private void refreshStatus(IMMessage message,View alertButton,ProgressBar progressBar) {// 消息状态
//		AudioAttachment attachment = (AudioAttachment) message.getAttachment();
//		MsgStatusEnum status = message.getStatus();
//		AttachStatusEnum attachStatus = message.getAttachStatus();
//
//		// alert button
//		if (TextUtils.isEmpty(attachment.getPath())) {
//			if (attachStatus == AttachStatusEnum.fail || status == MsgStatusEnum.fail) {
//				alertButton.setVisibility(View.VISIBLE);
//			} else {
//				alertButton.setVisibility(View.GONE);
//			}
//		}
//
//		// progress bar indicator
//		if (status == MsgStatusEnum.sending || attachStatus == AttachStatusEnum.transferring) {
//			progressBar.setVisibility(View.VISIBLE);
//		} else {
//			progressBar.setVisibility(View.GONE);
//		}
//
////		// unread indicator
////		if (message.getDirect() == MsgDirectionEnum.In && attachStatus == AttachStatusEnum.transferred  && status != MsgStatusEnum.read) {
////			unreadIndicator.setVisibility(View.VISIBLE);
////		} else {
////			unreadIndicator.setVisibility(View.GONE);
////		}
//	}
//
//
//
//	public List<IMMessage> getData() {
//		return data;
//	}
//
//	public void setData(List<IMMessage> data) {
//		this.data = data;
//		notifyDataSetChanged();
//	}

}


class ViewHolder {

    public ImageView userAvatarImageView;
    public TextView sendDateTextView;
    public TextView userNameTextView;

    public TextView textTextView;
    public ChatImageView photoImageView;
    public ChatImageView videoImageView;
    public LinearLayout mapLayout;
    public ImageView failImageView;
    public TextView sendTimeTextView;
    public TextView mapTextView;
    public ProgressBar sendingProgressBar;
    public TextView recoderTime;
    public View recoderAnim;
    public LinearLayout msgVoiceLayout;
    public LinearLayout msgContextLayout;
    public LinearLayout msgItemVoiceLayout;
    public ImageView msgMapImage;
    public LinearLayout textHintLayout;
    public TextView itemVip;
    public TextView itemHealth;
    public TextView itemRecord;
    public TextView itemMeasure;
    public RelativeLayout videoLayout;
    public ImageView videoPlayIv;
    public LinearLayout vipLayout;

    public ViewHolder(View convertView) {
        textHintLayout = convertView.findViewById(R.id.text_hint_layout);
        vipLayout = convertView.findViewById(R.id.vip_layout);
        itemVip = (TextView) convertView.findViewById(R.id.item_vip);
        itemHealth = (TextView) convertView.findViewById(R.id.item_health);
        itemRecord = (TextView) convertView.findViewById(R.id.item_record);
        itemMeasure = (TextView) convertView.findViewById(R.id.item_measure);
        sendDateTextView = (TextView) convertView.findViewById(R.id.sendDateTextView);
        sendTimeTextView = (TextView) convertView.findViewById(R.id.sendTimeTextView);
        userAvatarImageView = (ImageView) convertView.findViewById(R.id.userAvatarImageView);
        userNameTextView = (TextView) convertView.findViewById(R.id.userNameTextView);
        textTextView = (TextView) convertView.findViewById(R.id.textTextView);
        photoImageView = (ChatImageView) convertView.findViewById(R.id.photoImageView);
        videoImageView = (ChatImageView) convertView.findViewById(R.id.videoImageView);
        videoLayout = convertView.findViewById(R.id.video_layout);
        videoPlayIv = convertView.findViewById(R.id.video_play_iv);
        failImageView = (ImageView) convertView.findViewById(R.id.failImageView);
        sendingProgressBar = (ProgressBar) convertView.findViewById(R.id.sendingProgressBar);
        recoderTime = (TextView) convertView.findViewById(R.id.recoder_time);

        recoderAnim = convertView.findViewById(R.id.recoder_anim);

        msgVoiceLayout = (LinearLayout) convertView.findViewById(R.id.msg_voice_layout);

        msgContextLayout = (LinearLayout) convertView.findViewById(R.id.msg_context_layout);
        mapLayout = (LinearLayout) convertView.findViewById(R.id.map_context_layout);
        mapTextView = (TextView) convertView.findViewById(R.id.map_textView);
        msgItemVoiceLayout = (LinearLayout) convertView.findViewById(R.id.msg_item_voice_layout);
        msgMapImage = (ImageView) convertView.findViewById(R.id.msg_map_image);


    }


}


